package diona.search

import engine.Messages.Search
import engine.SearchTaskHandler
import org.squeryl.annotations._
import net.liftweb.squerylrecord.RecordTypeMode._
import net.liftweb.record.{MetaRecord, Record}
import net.liftweb.record.field.{DateTimeField, StringField, LongField}
import java.util.Calendar
import net.liftweb.squerylrecord.KeyedRecord
import diona.model.{User, PublisherSchema}
import net.liftweb.common.Empty
import yasearch.YaBlogsSearch

/**
 * User: anton
 * Date: 03.07.11 13:31
 */
class SearchRequest extends Record[SearchRequest] with KeyedRecord[Long]
{
  override def meta = SearchRequest

  @Column(name = "id")
  override val idField = new LongField(this)

  val query = new StringField(this, "")
  val registrationDate = new DateTimeField(this, Calendar.getInstance())

  val userId = new LongField(this)
}

object SearchRequest extends SearchRequest with MetaRecord[SearchRequest]
{
  private lazy val table = PublisherSchema.searchRequests

  @volatile var getOrCreateByQuery: (User, String) => SearchRequest =
    (u, q) => inTransaction {
      val req: Option[SearchRequest] = table.where(r => r.query === q and r.userId === u.id).headOption
      req match {
        case Some(r) => r
        case None => {
          val request = SearchRequest
            .createRecord
            .query(q)
            .userId(u.id.is).
            registrationDate(Calendar.getInstance())
          table.insert(request)
          val task = SearchTask.create(request.id, SearchType.Yandex, YaBlogsSearch.buildUrl(q))
          SearchTaskHandler ! Search(task.id)
          request
        }
      }
    }

  @volatile var getAll: (User) => List[SearchRequest] = u => inTransaction {table.where(_.userId === u.id).toList}

  @volatile var byId: Long => SearchRequest = id => inTransaction {table.where(_.id === id).single}
}